<template>
  <div class="add-employee">
    <button class="add-employee-header" @click="() => $router.push('/announcement')">
      <el-icon>
        <ArrowLeftBold />
      </el-icon>返回
      <text>|</text>
    </button>
    <div class="add-employee-title" v-if="isEdit">修改公告</div>
    <div class="add-employee-title" v-else>添加公告</div>


  </div>
  <div class="add-employee-content">
    <el-form :inline="true" ref="ruleFormRef" style="max-width: 80%" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="公告标题:" prop="title" style="width: 350px; margin-right: 100px;">
        <el-input v-model="ruleForm.title" placeholder="请输入公告标题" />
      </el-form-item>
      <el-form-item label="公告排序:" prop="sort" style="width: 250px;">
        <el-input v-model="ruleForm.sort" placeholder="请输入公告排序" />
      </el-form-item>
      <el-form-item label="公告内容:" prop="content" style="width: 100%;">
        <div style="border: 1px solid #ccc;">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="mode" />
          <Editor style="height: 330px;  overflow-y: hidden;" v-model="ruleForm.content" :defaultConfig="editorConfig"
            :mode="mode" @onCreated="handleCreated" />
        </div>
      </el-form-item>
    </el-form>
    <div class="add-employee-btn">
      <el-button color="#626aef" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </div>
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ref, reactive, shallowRef, onMounted, onBeforeUnmount } from 'vue'
import { addAnnouncement, getAnnouncementById, updateAnnouncement } from '@/api/announcement.js'
import router from '@/router';
import { useUserStore } from '@/stores/user.js'
const userStore = useUserStore()

const formSize = ref('default')
const ruleFormRef = ref(null)
const ruleForm = reactive({
  id: '',
  title: '',
  content: '',
  sort: '',
})

const rules = reactive({
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' },],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' },],
  sort: [{ required: true, message: '请输入公告排序', trigger: 'blur' },],
})

// 提交表单
const submitForm = async (formEl) => {
  console.log('提交表单', ruleForm);

  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log('验证成功！', ruleForm)
      if (isEdit.value) {
        // 修改
        await updateAnnouncement(ruleForm)
          .then(() => {
            ElMessage.success('修改成功！')
            router.push('/announcement')
          })
          .catch(() => {
            ElMessage.error('修改失败！')
          })

      } else {
        // console.log('添加', ruleForm);
        await addAnnouncement(ruleForm).then(() => {
          ElMessage.success('提交成功！')
          resetForm(formEl)
        })
          .catch(() => {
            ElMessage.error('提交失败！')
          })
      }

    } else {
      console.log('提交错误！', fields)
    }
  })
}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

// 判断是否存在id
const isEdit = ref(false)

onMounted(async () => {
  // console.log(router.currentRoute.value.query);
  const id = router.currentRoute.value.query.id;
  if (id) {
    isEdit.value = true
    // console.log('id', id);
    getAnnouncementById(id).then((res) => {
      // console.log('res', res);
      Object.assign(ruleForm, res.data)
    })

  }
})

// 创建编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
// const valueHtml = ref('')
// 如果仅仅想排除掉某些菜单，其他都保留，可以使用 excludeKeys 来配置。
const toolbarConfig = {
  excludeKeys: [
    'headerSelect',
    'italic',
    'group-video',// 排除菜单组，写菜单组 key 的值即可
    // 'insertImage',
    'todo'
  ]
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      //上传图片配置
      server: 'http://localhost:7070/api/admin/common/upload', //上传接口地址
      fieldName: 'file', //上传文件名
      methods: 'post',
      // 自定义增加 http  header
      headers: {
        token: userStore.viewToken
      },
      // 最多可上传几个文件，默认为 100
      maxNumberOfFiles: 10,
      // 自定义插入图片
      customInsert(res, insertFn) {
        console.log(res);
        console.log(insertFn);
        insertFn(res.data);
      },
      // 单个文件上传成功之后
      onSuccess(file, res) {
        // console.log(`${file.name} 上传成功`, res);
        ElMessage.success(`${file.name} 上传成功`)
        editorConfig.customInsert && editorConfig.customInsert(res);
      },
      // 单个文件上传失败
      onFailed(file, res) {         
        // console.log(`${file.name} 上传失败`, res)
        ElMessage.error(`${file.name} 上传失败`)
      },
    },
  },
}
/* 
具体来说，Wangeditor 的 mode 属性可以接收不同的值，通常包括：

'default'：表示使用默认模式，显示所有的工具条和功能。
'simple'：表示使用简化模式，只显示基本的工具条和功能。
*/
const mode = ref('default')// 或 'simple'

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor) {
    editor.destroy()
  }
})

// 编辑器创建时的回调函数
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例
}


</script>

<style lang="scss">
.add-employee {
  display: flex;
  align-items: center;

  .add-employee-header {
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    background: none;
    color: inherit;
    padding: 0;
    cursor: pointer;

    .el-icon {
      margin-right: 3px;
    }

    text {
      margin: 0 10px;
      color: #999;
      font-size: 14px;
      border-radius: 5px;
    }
  }

  .add-employee-title {
    font-size: 18px;
  }
}

.add-employee-content {
  margin-top: 10px;
  padding: 10px;
  background-color: #fff;

  .el-form {
    margin: 20px 0 0 100px;

    .avatar-uploader {
      width: 178px;
      height: 178px;
      display: block;
      border: 2px dashed #d9d9d9;

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
      }

      .avatar {
        width: 178px;
        height: 178px;

      }
    }
  }

  .add-employee-btn {
    margin-top: 10px;
    padding-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: 1px solid var(--el-border-color);

  }
}
</style>